<?php

namespace App\Http\Controllers\App\V1;

use App\Response\Response;
use App\Services\Tools\ZeGoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\BaseController;

class ZegoController extends BaseController
{

    //删除流
    public function delStream(Request $request)
    {
        $room_id = $request->input('room_id');
        $user_id = $request->input('user_id');
        $nickname = app('model_user_data')->getUserNickname($user_id);
        $token = $this->getZegoToken();
        $zego_appid = (int)env('ZEGO_APPID');
        $url = 'https://liveroom'.$zego_appid.'-api.zego.im/cgi/delstream';

        $data = [
            'access_token' => $token,
            'version'      => 1,
            'seq'          => 1,
            'room_id'      => $room_id,
            'user_account' => $user_id,
            'nick_name'    => $nickname,
            'stream_id'    => $room_id.'_'.$user_id
        ];
        $result = $this->Post($url, $data);
        return Response::sendData($result);
    }

    //即构流创建回调
    public function callbackCreateStream(Request $request)
    {
        $params = $request->input();
        $appid = $params['appid'] ?? '';
        if ($appid == env('ZEGO_APPID')) {
            $room_id = $params['room_id'] ?? 0;
            $user_id = $params['user_id'] ?? 0;
            $create_time = $params['create_time'] ?? 0;
            if ($room_id && $user_id && $create_time) {
                app('model_room_pit_zego')->firstOrCreate(
                    ['room_id' => $room_id, 'user_id' => $user_id],
                    ['room_id' => $room_id, 'user_id' => $user_id, 'add_time' => $create_time]
                );
            }
        }
        exit(1);
    }

    //即构流关闭回调
    public function callbackCloseStream(Request $request)
    {
        $params = $request->input();
        $appid = $params['appid'] ?? '';
        if ($appid == env('ZEGO_APPID')) {
            $room_id = $params['room_id'] ?? 0;
            $user_id = $params['user_id'] ?? 0;
            if ($room_id && $user_id) {
                app('model_room_pit_zego')->where(['room_id' => $room_id, 'user_id' => $user_id])->delete();
            }
        }
        exit(1);
    }


    public function getZegoToken()
    {
        $token = app('redis')->get('zego:access_token');
        if ($token) {
            return $token;
        }
        $zego_appid = (int)env('ZEGO_APPID');

        $access_token_url = 'https://liveroom'.$zego_appid.'-api.zego.im/cgi/token';
        $token_result = $this->Post(
            $access_token_url,
            [
                'version' => 1,
                'seq'     => time(),
                'app_id'  => $zego_appid,
                'token'   => $this->createZegoToken()
            ]
        );
        $result = json_decode($token_result, true);
        $access_token = $result['data']['access_token'] ?? '';
        if ($access_token) {
            app('redis')->setex('zego:access_token', 3500, $access_token);
        }
        return $access_token;
    }

    public function createZegoToken()
    {
        $zego_appid = env('ZEGO_APPID');
        $current_time = time();                                    //获取当前时间
        $expired_time = $current_time + 86400;                     //过期时间，单位：秒
        $app_id = $zego_appid;                                     // Int类型,这里填写各自分配的appid
        $server_app_secret = env('ZEGO_SERVER_SECRET');            // 这里填写对应的ServerSecret
        $nonce = str_random();                                     //自定义的随机数
        $origin = $app_id.$server_app_secret.$nonce.$expired_time;
        $hash = md5($origin);
        $token = [
            'ver'     => 1,
            'hash'    => $hash,
            'nonce'   => $nonce,
            'expired' => $expired_time
        ];
        $token = json_encode($token);
        $encode_token = base64_encode($token);
        return $encode_token;
    }


    public function Get($url)
    {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //返回结果
        return $output;
    }

    public function Post($url, $postData)
    {
        $data_string = json_encode($postData);
        $ch = curl_init();
        // 设置超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            ['Content-Type: application/json; charset=utf-8', 'Content-Length: '.strlen($data_string)]
        );
        $output = curl_exec($ch);
        curl_close($ch);
        //返回结果
        return $output;
    }

    public function musicPlayerModel(Request $request)
    {
        $config = app("model_config")->getValue('MUSIC_PLAYER_MODEL');

        return Response::sendData(["model" => (int)$config]);
    }

    // 歌曲
    public function songs(Request $request)
    {
        $keywords = $request->query("keyword", "");
        $page = (int)$request->query("page", 1);
        $roomId = (int)$request->query("room_id", 0);
        $userId = (int)UID;

        $server = new ZeGoService($roomId, $userId);
        $res = $server->getSongsTop($keywords, $page);

        return Response::sendData($res);
    }
}
